var express = require('express');
var router = express.Router();
var models = require('../models')
var Op = models.Sequelize.Op

/* GET Children info */
router.get('/', async function (req, res, next) {
    try {
        if (req.query) {
            const { rightId } = req.query
            if (rightId) {
                var childrens = await models.Children.findAll({
                    where: { [Op.and]: [{ rightId }] },
                    order: [['id', 'ASC']],
                    include: {
                        model: models.Right
                    }
                })
                if (childrens) {
                    res.json({ childrens })
                } else {
                    res.json({ msg: "不存在相关信息" })
                }
            } else {
                var childrens = await models.Children.findAll()
                res.json({ childrens })
            }
        }
    } catch (e) {
        console.log(e);
    }
});

// 修改权限信息
router.put('/:id', async function (req, res, next) {
    const id = req.params.id
    const { key, title, pagePermission, grade } = JSON.parse(req.query.data)
    try {
        var users = await models.Children.update({
            key, title, pagePermission, grade
        }, { where: { id } })

        res.json({ users })
    } catch (e) {
        console.log(e)
    }
})

// 修改权限状态
router.put('/pagePermission/:id', async function (req, res, next) {
    const id = req.params.id
    const pagePermission = JSON.parse(req.query.pagePermission)
    // console.log(roleState);
    try {
        var users = await models.Children.update({
            pagePermission
        }, { where: { id } })
        res.json({ users })
    } catch (e) {
        console.log(e)
    }
})

// 删除权限信息
router.delete('/:id', async function (req, res, next) {
    const id = req.params.id
    var children = await models.Children.findByPk(id)
    if (children) {
        children.destroy()
        res.json({ msg: '删除成功' })
    } else {
        res.json({ msg: '不存在该数据' })
    }
})

module.exports = router;
